<template>
  <div class="inventory-tasks-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <div class="search-header">
        <span class="search-title">搜索条件</span>
        <div class="search-buttons">
          <el-button type="primary" @click="handleSearch" size="small">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearchForm" size="small">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </div>
      </div>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="盘点编号" label-width="70px">
              <el-input 
                v-model="searchForm.inventoryCode" 
                placeholder="请输入" 
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="盘点名称" label-width="70px">
              <el-input 
                v-model="searchForm.inventoryName" 
                placeholder="请输入" 
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盘点日期" label-width="70px">
              <el-date-picker
                v-model="searchForm.inventoryTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="状态" label-width="50px">
              <el-select 
                v-model="searchForm.states" 
                placeholder="请选择" 
                clearable
                style="width: 100%"
                size="small"
              >
                <el-option label="待审核" value="1"/>
                <el-option label="审核成功" value="2"/>
                <el-option label="审核失败" value="3"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button plain class="op-btn" @click="handleAdd">
        <el-icon><Plus /></el-icon> 新增
      </el-button>
   
      <el-button plain class="op-btn" @click="handleDelete">
        <el-icon><Delete /></el-icon> 删除
      </el-button>
      <el-button plain class="op-btn" @click="handleRefresh">
        <el-icon><Refresh /></el-icon> 刷新
      </el-button>
      <el-button plain class="op-btn" @click="handleExport">
        <el-icon><Upload /></el-icon> 导出
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
        :data="tableData"
        border
        style="width: 100%;"
        header-cell-class-name="table-header"
        row-class-name="table-row"
        :row-style="{height: '50px'}"
        :cell-style="{fontSize: '14px', textAlign: 'center', verticalAlign: 'middle', padding: '2px'}"
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="inventoryCode" label="盘点编号" min-width="150"/>
        <el-table-column prop="inventoryName" label="盘点名称" min-width="150"/>
        <el-table-column prop="inventoryTime" label="盘点日期" min-width="120"/>
        <el-table-column prop="inventoryProple" label="盘点人" min-width="100"/>
        <el-table-column prop="states" label="状态" min-width="80">
          <template #default="scope">
            <el-tag
              :type="scope.row.states==1?'warning':scope.row.states==2?'success':'info'"
              effect="dark"
              size="small"
            >
              {{ scope.row.states==1?'待审核':scope.row.states==2?'审核成功':'审核失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button 
              type="danger" 
              size="small" 
              plain 
              @click.stop="handleDeleteSingle(scope.row)"
              :disabled="scope.row.states === 2"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-area">
        <el-pagination
          :current-page="paging.pageindex"
          :page-size="paging.pagesize"
          :page-sizes="[10, 20, 30, 50]"
          :total="paging.total"
          layout="total, sizes, prev, pager, next"
          @current-change="val => { paging.pageindex = val; handleSearch(); }"
          @size-change="val => { paging.pagesize = val; paging.pageindex = 1; handleSearch(); }"
          background
          small
        />
      </div>
    </div>

    <!-- 新增盘点单弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增盘点单"
      width="66%"
      :close-on-click-modal="false"
    >
      <el-form :model="addForm" label-width="100px" class="add-form">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="盘点单号：">
              <el-input v-model="addForm.inventoryCode" placeholder="可不填写，自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单人：">
              <el-input v-model="addForm.creator" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单时间：">
              <el-date-picker v-model="addForm.createTime" type="date" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：">
              <el-input v-model="addForm.remark" type="textarea" :rows="3" maxlength="300" show-word-limit placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="product-table-title">
        <span>产品信息</span>
        <div>
          <el-button type="success" size="small" @click="handleBatchSave" style="margin-right: 10px;">批量保存</el-button>
          <el-button type="primary" size="small" @click="handleSelectProduct">+ 选择产品</el-button>
        </div>
      </div>
      <el-table :data="addProductList" border class="add-product-table" style="margin-top: 12px; min-width: 100%;">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="taskCode" label="产品编码" width="120"/>
        <el-table-column prop="taskName" label="产品名称" width="180"/>
        <el-table-column prop="inventoryType" label="规格" width="140"/>
        <el-table-column prop="bin" label="库位" width="120">
          <template #default="scope">
            <el-input v-model="scope.row.bin" placeholder="输入" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="inventoryScheme" label="批次" width="120">
          <template #default="scope">
            <el-input v-model="scope.row.inventoryScheme" placeholder="输入" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="number" label="库存" width="80"/>
        <el-table-column prop="count" label="盘点数" width="100">
          <template #default="scope">
            <el-input v-model="scope.row.count" placeholder="输入" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="profit" label="盈亏" width="80">
          <template #default="scope">
            <span :class="{ 'profit-positive': scope.row.profit > 0, 'profit-negative': scope.row.profit < 0 }">
              {{ calculateProfit(scope.row) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button 
              class="save-btn"
              :type="scope.row.saved ? 'success' : 'primary'" 
              size="small" 
              @click="handleSaveProduct(scope.row)"
              :disabled="scope.row.saved"
            >
              {{ scope.row.saved ? '已保存' : '保存' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="add-dialog-footer">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择产品弹框 -->
    <el-dialog
      v-model="selectProductDialogVisible"
      title="选择产品"
      width="60%"
      :close-on-click-modal="false"
    >
      <div class="select-product-search-bar">
        <el-form :inline="true" :model="selectProductQuery">
          <el-form-item label="产品编码：">
            <el-input v-model="selectProductQuery.code" placeholder="请输入编码" />
          </el-form-item>
          <el-form-item label="产品名称：">
            <el-input v-model="selectProductQuery.name" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSelectProductSearch">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="selectProductList"
        border
        class="select-product-table"
        @selection-change="handleSelectProductSelection"
        :row-key="row => row.taskCode"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="taskCode" label="产品编码" width="120"/>
        <el-table-column prop="taskName" label="产品名称" width="150"/>
        <el-table-column prop="inventoryType" label="规格"/>
        <el-table-column prop="inventoryTime" label="盘点日期"/>
        <el-table-column prop="bin" label="库位" width="120"/>
      </el-table>
      <div class="select-product-pagination">
        <el-pagination
          :current-page="paging1.pageindex"
          :page-size="paging1.pagesize"
          :total="paging1.total"
          layout="prev, pager, next, jumper, ->, total, sizes"
          :page-sizes="[4, 6, 8,10]"
          @current-change="val => { paging1.pageindex = val; handleSelectProductSearch(); }"
          @size-change="val => { paging1.pagesize = val; paging1.pageindex = 1; handleSelectProductSearch(); }"
        />
      </div>
      <template #footer>
        <div class="select-product-footer">
          <el-button @click="selectProductDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleSelectProductConfirm">选择</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted,watch } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Upload } from '@element-plus/icons-vue'
import http from '@/api/http'
// 导入Excel导出所需的库
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

// 搜索表单数据
const searchForm = reactive({
    inventoryCode: '',
    inventoryName: '',
    inventoryTime: '',
    states: ''
})
const paging=reactive({
    pageindex:1,
    pagesize:4,
    total:0,
})
watch(paging,()=>{
    handleSearch()
})
const paging1 = reactive({
  pageindex: 1,
  pagesize: 4,
  total: 0
})
watch(paging1,()=>{
    handleSelectProductSearch()
})

const tableData = ref([])
// 选中的表格行
const selectedRows = ref([])

// 表格选择变更处理
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 查询方法
const handleSearch = async () => {
  try {
    const res = await http.get(`api/Inventorytasks/QueryInventorytasks?InventoryCode=${searchForm.inventoryCode}&InventoryName=${searchForm.inventoryName}&InventoryTime=${searchForm.inventoryTime}&States=${searchForm.states}&PageIndex=${paging.pageindex}&PageSize=${paging.pagesize}`);
    console.log('查询返回数据:', res);
    
    if (res && res.rows) {
      // 确保状态字段的格式一致性
      tableData.value = res.rows.map(row => ({
        ...row,
        // 确保states是数字类型
        states: typeof row.states === 'string' ? parseInt(row.states) : row.states,
        // 清空bin和inventoryScheme字段，确保用户能自行输入
        bin: '',
        inventoryScheme: ''
      }));
      paging.total = res.total || 0;
    } else {
      tableData.value = [];
      paging.total = 0;
      console.warn('查询返回数据格式不符合预期:', res);
    }
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('查询失败: ' + (error.message || '未知错误'));
    tableData.value = [];
    paging.total = 0;
  }
}

const selectProductDialogVisible = ref(false)
const handleSelectProduct = () => {
  selectProductDialogVisible.value = true;
};
const selectProductQuery = reactive({
  code: '',
  name: ''
})
const selectProductList = ref([])
const handleSelectProductSearch = async () => {
  try {
    // 添加过滤条件，确保不显示无效数据
    const res = await http.get(`api/Inventorytasks/InventorytasksList?TaskCode=${selectProductQuery.code}&TaskName=${selectProductQuery.name}&PageIndex=${paging1.pageindex}&PageSize=${paging1.pagesize}`);
    
    if (res && res.rows) {
      // 过滤掉无效数据，但不过滤掉已选择的产品
      selectProductList.value = res.rows.filter(item => {
        // 确保产品有基本信息
        return item.taskCode && item.taskName;
      }).map(item => {
        // 清空bin和inventoryScheme字段，确保不会自动填充
        return {
          ...item,
          bin: '', // 确保库位字段为空
          inventoryScheme: '' // 确保批次字段为空
        };
      });
      
      // 标记已选择的产品
      selectProductList.value.forEach(product => {
        // 检查产品是否已经在addProductList中
        const existingProduct = addProductList.value.find(p => p.taskCode === product.taskCode);
        if (existingProduct) {
          product._disabled = true; // 标记为已选择，可选择禁用或显示特殊标记
          product._selected = true; // 预选中已添加的产品
        }
      });
      
      paging1.total = res.total || selectProductList.value.length;
    } else {
      selectProductList.value = [];
      paging1.total = 0;
    }
    console.log('产品列表数据:', selectProductList.value);
  } catch (error) {
    console.error('获取产品列表失败:', error);
    ElMessage.error('获取产品列表失败');
    selectProductList.value = [];
    paging1.total = 0;
  }
}

const addProductList = ref([])
const selectProductSelection = ref([])
const handleSelectProductSelection = (selection) => {
  selectProductSelection.value = selection
}
const handleSelectProductConfirm = () => {
  if (selectProductSelection.value.length === 0) {
    ElMessage.warning('请至少选择一个产品');
    return;
  }
  
  let addedCount = 0;
  
  selectProductSelection.value.forEach(item => {
    // 验证产品数据是否有效
    if (!item.taskCode || !item.taskName) {
      console.warn('跳过无效产品:', item);
      return; // 跳过无效产品
    }
    
    // 检查产品是否已经添加
    const exists = addProductList.value.some(row => row.taskCode === item.taskCode);
    if (!exists) {
      addProductList.value.push({
        id: 0,
        taskCode: item.taskCode || '',
        taskName: item.taskName || '',
        inventoryType: item.inventoryType || '',
        bin: item.bin || '',
        inventoryScheme: item.inventoryScheme || '',
        inventoryTime: new Date().toISOString().split('T')[0],
        inventoryProple: addForm.value.creator || '管理员',
        states: 1,
        number: item.number || '0',
        count: '',
        profit: 0,
        saved: false,
        cause: ''
      });
      addedCount++;
    }
  });
  
  selectProductDialogVisible.value = false;
  
  if (addedCount > 0) {
    ElMessage.success(`已添加 ${addedCount} 个产品`);
  } else {
    ElMessage.info('没有新增产品，所选产品已在列表中');
  }
}

const addDialogVisible = ref(false)
const addForm = ref({
  "id": 0,
  "taskCode": "",
  "taskName": "",
  "inventoryType": "",
  "inventoryScheme": "",
  "inventoryTime": "",
  "inventoryProple": "",
  "states": "",
  "inventoryCode": "",
  "inventoryName": "",
  "cause": "",
  "bin": "",
  "number": "",
  "count": "",
  "profit": ""
})

const handleAdd = () => {
  // 自动生成盘点单号
  const now = new Date();
  const pad = n => n.toString().padStart(2, '0');
  const code = `PD${now.getFullYear()}${pad(now.getMonth()+1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
  addForm.value = {
   "id": 0,
  "taskCode": "",
  "taskName": "",
  "inventoryType": "",
  "inventoryScheme": "",
  "inventoryTime": "",
  "inventoryProple": "",
  "states": "",
  "inventoryCode": code,
  "inventoryName": "",
  "cause": "",
  "bin": "",
  "number": "",
  "count": "",
  "profit": ""
  }
  
  addDialogVisible.value = true
}

const handleBatchSave = async () => {
  if (addProductList.value.length === 0) {
    ElMessage.warning('没有产品需要保存')
    return
  }

  // 检查是否有产品缺少盘点数
  const missingCountProducts = addProductList.value.filter(item => !item.count);
  if (missingCountProducts.length > 0) {
    ElMessage.warning(`有 ${missingCountProducts.length} 个产品未填写盘点数量，请先填写`);
    return;
  }

  ElMessageBox.confirm(
    '确定要保存所有产品的盘点数据吗？',
    '确认提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
      dangerouslyUseHTMLString: false
    }
  ).then(() => {
    // 计算所有产品的盈亏数量并在本地保存
    addProductList.value.forEach(item => {
      if (item.count && item.number) {
        item.profit = Number(item.count) - Number(item.number);
      }
      
      // 确保所有必要字段都有值
      item.id = item.id || 0;
      item.inventoryTime = item.inventoryTime || new Date().toISOString().split('T')[0];
      item.inventoryProple = item.inventoryProple || addForm.value.creator || '管理员';
      item.states = item.states || 1;
      item.inventoryCode = item.inventoryCode || addForm.value.inventoryCode;
      item.inventoryName = item.inventoryName || addForm.value.inventoryName || '盘点任务';
      item.cause = item.cause || addForm.value.cause || '';
      
      item.saved = true;
    });
    
    console.log('批量保存产品数据:', addProductList.value);
    
    ElMessage({
      message: '所有产品已在本地保存，提交盘点单时才会保存到数据库',
      type: 'success'
    });
  }).catch(() => {
    // 用户取消操作
  });
}

const handleSaveProduct = async (row) => {
  // 检查必填字段
  if (!row.count) {
    ElMessage.warning('请输入盘点数量');
    return;
  }

  ElMessageBox.confirm(
    '确定要保存该产品的盘点数据吗？',
    '确认提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
      dangerouslyUseHTMLString: false
    }
  ).then(() => {
    // 计算盈亏数量
    if (row.count && row.number) {
      row.profit = Number(row.count) - Number(row.number);
    }
    
    // 确保所有必要字段都有值
    row.id = row.id || 0;
    row.inventoryTime = row.inventoryTime || new Date().toISOString().split('T')[0];
    row.inventoryProple = row.inventoryProple || addForm.value.creator || '管理员';
    row.states = row.states || 1;
    row.inventoryCode = row.inventoryCode || addForm.value.inventoryCode;
    row.inventoryName = row.inventoryName || addForm.value.inventoryName || '盘点任务';
    row.cause = row.cause || addForm.value.cause || '';
    
    // 仅在本地标记为已保存，不发送API请求
    row.saved = true;
    
    console.log('本地保存产品数据:', row);
    
    // 显示成功消息
    ElMessage({
      message: '产品已在本地保存，提交盘点单时才会保存到数据库',
      type: 'success'
    });
  }).catch(() => {
    // 用户取消操作
  });
}

const submitForm = async () => {
  if (!addForm.value.inventoryCode) {
    ElMessage.warning('请输入盘点单号')
    return
  }
  
  if (addProductList.value.length === 0) {
    ElMessage.warning('请添加产品信息')
    return
  }

  // 检查是否有未保存的产品
  const unsavedProducts = addProductList.value.filter(item => !item.saved);
  if (unsavedProducts.length > 0) {
    ElMessageBox.confirm(
      `有 ${unsavedProducts.length} 个产品未保存，是否继续提交？`,
      '提示',
      {
        confirmButtonText: '继续提交',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      // 用户确认继续，执行提交
      doSubmit();
    }).catch(() => {
      // 用户取消提交
    });
  } else {
    // 所有产品都已保存，直接提交
    doSubmit();
  }
}

// 实际执行提交的函数
const doSubmit = async () => {
  try {
    // 显示加载提示
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交数据...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    // 准备提交数据
    const now = new Date();
    const dateStr = now.toISOString().split('T')[0];
    
    // 创建提交数据结构
    const inventoryTask = {
      id: 0,
      inventoryCode: addForm.value.inventoryCode,
      inventoryName: addForm.value.inventoryName || '盘点任务',
      inventoryTime: dateStr,
      inventoryProple: addForm.value.creator || '管理员',
      remark: addForm.value.remark || '',
      states: 1,
      cause: addForm.value.cause || '',
      bin: '',
      inventoryType: '',
      // 直接使用已保存的产品数据，不再重新构建
      items: addProductList.value.map(item => {
        // 确保计算盈亏值已更新
        const number = Number(item.number) || 0;
        const count = Number(item.count) || 0;
        const profit = count - number;
        
        // 返回已经保存的完整产品数据，只更新必要字段
        return {
          ...item, // 保留所有已保存的字段
          profit: profit, // 确保盈亏计算正确
          inventoryCode: addForm.value.inventoryCode, // 确保关联到当前盘点单
          inventoryName: addForm.value.inventoryName || '盘点任务'
        };
      })
    };
    
    console.log('提交数据:', JSON.stringify(inventoryTask, null, 2));
    
    // 发送请求前添加日志，专门查看库位和批次字段
    console.log('库位和批次字段检查:');
    inventoryTask.items.forEach((item, index) => {
      console.log(`产品 ${index+1} - ${item.taskName}:`);
      console.log(`  库位: "${item.bin}"`);
      console.log(`  批次: "${item.inventoryScheme}"`);
    });

    // 数据转换函数，确保字段名称与后端一致
    const dataToSubmit = convertDataForBackend(inventoryTask);
    console.log('转换后的提交数据:', JSON.stringify(dataToSubmit, null, 2));

    // 检查转换后的库位和批次字段
    console.log('转换后的库位和批次字段检查:');
    if (dataToSubmit.Items && Array.isArray(dataToSubmit.Items)) {
      dataToSubmit.Items.forEach((item, index) => {
        console.log(`产品 ${index+1} - ${item.TaskName}:`);
        console.log(`  库位: "${item.Bin}"`);
        console.log(`  批次: "${item.InventoryScheme}"`);
      });
    }

    // 发送请求
    const res = await http.post('api/Inventorytasks/CreateInventorytasks', dataToSubmit, true, {
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    });
    console.log('提交响应:', res);
    
    // 关闭加载提示
    loading.close();
    
    // 无论返回什么，只要没有抛出异常就认为成功
    ElMessage.success('盘点单提交成功');
    addDialogVisible.value = false;
    addProductList.value = []; // 清空产品列表
    handleSearch(); // 刷新表格数据
  } catch (error) {
    console.error('提交异常:', error);
    ElMessage.error('提交失败: ' + (error.message || '服务器异常'));
  }
}

// 数据转换函数，确保字段名称与后端一致
const convertDataForBackend = (data) => {
  // 深拷贝避免修改原对象
  const result = JSON.parse(JSON.stringify(data));
  
  // 转换顶级字段
  result.InventoryCode = result.inventoryCode;
  result.InventoryName = result.inventoryName;
  result.InventoryTime = result.inventoryTime;
  result.InventoryProple = result.inventoryProple;
  result.States = result.states;
  result.Cause = result.cause;
  result.Bin = result.bin;
  result.InventoryType = result.inventoryType;
  result.Remark = result.remark;
  
  // 转换items内部的字段
  if (result.items && Array.isArray(result.items)) {
    result.Items = result.items.map(item => {
      return {
        Id: item.id,
        TaskCode: item.taskCode,
        TaskName: item.taskName,
        InventoryType: item.inventoryType,
        InventoryScheme: item.inventoryScheme,
        InventoryTime: item.inventoryTime,
        InventoryProple: item.inventoryProple,
        States: item.states,
        Bin: item.bin,
        Number: item.number,
        Count: item.count,
        Profit: item.profit,
        InventoryCode: item.inventoryCode,
        InventoryName: item.inventoryName,
        Cause: item.cause
      };
    });
    
    // 删除原始字段
    delete result.items;
  }
  
  // 删除原始小写字段
  delete result.inventoryCode;
  delete result.inventoryName;
  delete result.inventoryTime;
  delete result.inventoryProple;
  delete result.states;
  delete result.cause;
  delete result.bin;
  delete result.inventoryType;
  delete result.remark;
  
  return result;
};

const handleRefresh = () => {
  // 重新加载数据
  handleSearch()
  ElMessage.success('数据已刷新')
}

const handleEdit = (row) => {
  ElMessage.info('编辑功能待实现')
}

const handleDelete = () => {
  // 检查是否有选中的行
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条数据进行删除')
    return
  }
  
  // 检查是否有已审核成功的数据，不允许删除
  const hasApprovedRows = selectedRows.value.some(row => row.states === 2)
  if (hasApprovedRows) {
    ElMessage.warning('已审核成功的盘点任务不能删除，请重新选择')
    return
  }

  // 获取选中行的ID和编号
  const selectedIds = selectedRows.value.map(row => row.id).join(',')
  const selectedCodes = selectedRows.value.map(row => row.inventoryCode).join('、')
  
  // 确认删除
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条盘点任务吗？\n盘点编号：${selectedCodes}`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: false
    }
  ).then(async () => {
    // 显示加载提示
    const loading = ElLoading.service({
      lock: true,
      text: '正在删除...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    try {
      // 发送删除请求，使用post替代delete
      const res = await http.post(`api/Inventorytasks/DelInventorytasks?ids=${selectedIds}`)
      
      loading.close()
      
      if (res && res.status) {
        ElMessage.success('删除成功')
        // 刷新表格数据
        handleSearch()
        // 清空选中
        selectedRows.value = []
      } else {
        ElMessage.error(res?.message || '删除失败')
      }
    } catch (error) {
      loading.close()
      console.error('删除失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 导出功能实现
const handleExport = () => {
  // 检查是否有选中的行，如果没有选中则导出全部数据
  const dataToExport = selectedRows.value.length > 0 ? selectedRows.value : tableData.value
  
  if (dataToExport.length === 0) {
    ElMessage.warning('没有数据可导出')
    return
  }
  
  // 显示加载提示
  const loading = ElLoading.service({
    lock: true,
    text: '正在准备导出数据...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    // 准备导出数据
    const exportData = dataToExport.map(item => {
      // 获取状态文本
      let statusText = '未知'
      if (item.states === 1) statusText = '待审核'
      else if (item.states === 2) statusText = '审核成功'
      else if (item.states === 3) statusText = '审核失败'
      
      return {
        '盘点编号': item.inventoryCode || '',
        '盘点名称': item.inventoryName || '',
        '盘点日期': item.inventoryTime || '',
        '盘点人': item.inventoryProple || '',
        '状态': statusText
      }
    })
    
    // 创建工作簿
    const worksheet = XLSX.utils.json_to_sheet(exportData)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '盘点任务列表')
    
    // 设置列宽
    const columnWidths = [
      { wch: 20 }, // 盘点编号
      { wch: 20 }, // 盘点名称
      { wch: 15 }, // 盘点日期
      { wch: 15 }, // 盘点人
      { wch: 10 }  // 状态
    ]
    worksheet['!cols'] = columnWidths
    
    // 生成Excel文件
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    
    // 获取当前时间作为文件名的一部分
    const now = new Date()
    const timestamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`
    
    // 下载文件名根据是否选择了部分数据来确定
    const fileName = selectedRows.value.length > 0 && selectedRows.value.length < tableData.value.length
      ? `盘点任务列表_已选${selectedRows.value.length}条_${timestamp}.xlsx` 
      : `盘点任务列表_全部_${timestamp}.xlsx`
    
    saveAs(blob, fileName)
    
    loading.close()
    ElMessage.success('导出成功')
  } catch (error) {
    loading.close()
    console.error('导出异常:', error)
    ElMessage.error('导出失败: ' + (error.message || '未知错误'))
  }
}

const calculateProfit = (row) => {
  if (row.count && row.number) {
    const profit = Number(row.count) - Number(row.number);
    if (profit > 0) {
      return `+${profit.toFixed(2)}`;
    } else {
      return profit.toFixed(2);
    }
  }
  return '0.00';
}

// 重置搜索表单
const resetSearchForm = () => {
  searchForm.inventoryCode = ''
  searchForm.inventoryName = ''
  searchForm.inventoryTime = ''
  searchForm.states = ''
  handleSearch()
  ElMessage.success('搜索条件已重置')
}

const handleDeleteSingle = (row) => {
  // 检查状态，已审核成功的不能删除
  if (row.states === 2) {
    ElMessage.warning('已审核成功的盘点任务不能删除')
    return
  }
  
  // 确认删除
  ElMessageBox.confirm(
    `确定要删除盘点任务 "${row.inventoryCode}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    // 显示加载提示
    const loading = ElLoading.service({
      lock: true,
      text: '正在删除...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    try {
      // 发送删除请求，使用post替代delete
      const res = await http.post(`api/Inventorytasks/DelInventorytasks?ids=${row.id}`)
      
      loading.close()
      
      if (res && res.status) {
        ElMessage.success('删除成功')
        // 刷新表格数据
        handleSearch()
      } else {
        ElMessage.error(res?.message || '删除失败')
      }
    } catch (error) {
      loading.close()
      console.error('删除失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
    }
  }).catch(() => {
    // 用户取消删除
  })
}

onMounted(()=>{
    handleSearch()
    handleSelectProductSearch()
})
</script>

<style scoped>
.inventory-tasks-container {
  padding: 10px;
}

.search-area {
  background-color: #fff;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 10px;
  box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.05);
  max-width: 100%;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.search-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.search-buttons {
  display: flex;
  gap: 8px;
}

.search-form {
  width: 100%;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  width: 100%;
}

.search-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.search-form :deep(.el-input),
.search-form :deep(.el-select),
.search-form :deep(.el-date-editor) {
  width: 100%;
}

.search-form :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.search-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.search-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.operation-area {
  margin-bottom: 10px;
  display: flex;
  gap: 8px;
  max-width: 100%;
}

.op-btn {
  background: #f5f7fa;
  color: #606266;
  border: 1px solid #e4e7ed;
  font-weight: 500;
  font-size: 13px;
  padding: 6px 12px;
  border-radius: 4px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  height: 32px;
}

.op-btn .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.op-btn:hover {
  background: #ebeef5;
  color: #409eff;
  border-color: #c0c4cc;
}

.table-area {
  background: #fff;
  padding: 12px 12px 8px 12px;
  border-radius: 6px;
  box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 10px;
  max-width: 100%;
}

.table-header {
  background: #f5f7fa !important;
  font-weight: bold;
  font-size: 14px;
  color: #333;
  padding: 4px 0;
  height: 40px;
}

.table-row:hover td {
  background: #f0f9ff !important;
}

.el-table .el-table__cell {
  padding: 4px 0;
}

.el-table .el-tag {
  font-size: 12px;
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

.table-op-btn {
  margin-right: 8px;
  border-radius: 6px;
  transition: background 0.2s, color 0.2s;
}

.table-op-btn:hover {
  color: #409eff;
  background: #f0f9ff;
}

.pagination-area {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.detail-info {
  margin-bottom: 18px;
  font-size: 16px;
  color: #333;
}
.detail-info .label {
  font-weight: 600;
  color: #666;
  margin-right: 8px;
}
.el-dialog__body {
  padding-top: 18px;
  padding-bottom: 0;
}

.add-form {
  margin-bottom: 18px;
  background: #f8fafc;
  border-radius: 8px;
  padding: 18px 18px 0 18px;
}
.add-form .el-form-item {
  margin-bottom: 18px;
}
.add-form .el-input,
.add-form .el-date-editor {
  width: 100%;
}

.product-table-title {
  font-weight: bold;
  font-size: 16px;
  margin: 18px 0 6px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.add-product-table {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 12px;
}
.add-product-table .el-table__header th {
  background: #f5f7fa;
  font-weight: bold;
  font-size: 15px;
  color: #333;
}
.add-product-table .el-table__row {
  height: 48px;
}
.add-product-table .el-table__cell {
  text-align: center;
  font-size: 15px;
}
.add-product-table .el-table__row:hover td {
  background: #f0f9ff !important;
}
.add-product-table .el-input {
  min-width: 60px;
  font-size: 14px;
}
.add-product-table .el-button {
  font-size: 14px;
  padding: 2px 10px;
}

.add-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 8px;
}

/* 选择产品弹框样式优化 */
.el-dialog__wrapper .el-dialog {
  border-radius: 14px;
  box-shadow: 0 6px 32px 0 rgba(0,0,0,0.12);
  padding-bottom: 0;
}

.select-product-search-bar {
  margin-bottom: 18px;
  padding: 8px 0 0 0;
  display: flex;
  align-items: center;
  gap: 24px;
}
.select-product-search-bar .el-form-item {
  margin-right: 18px;
}
.select-product-search-bar .el-input {
  width: 180px;
}

.select-product-table {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 12px;
}
.select-product-table .el-table__header th {
  background: #f5f7fa;
  font-weight: bold;
  font-size: 15px;
  color: #333;
}
.select-product-table .el-table__row {
  height: 48px;
}
.select-product-table .el-table__cell {
  text-align: center;
  font-size: 15px;
}
.select-product-table .el-table__row:hover td {
  background: #f0f9ff !important;
}

.select-product-pagination {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.select-product-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 8px;
}

.save-btn {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.save-btn:hover {
  opacity: 0.9;
}

.profit-positive {
  color: #67C23A;
  font-weight: bold;
}

.profit-negative {
  color: #F56C6C;
  font-weight: bold;
}
</style>